<?php
class ReportAction extends AdminbaseAction
{

	protected $dao;
    function _initialize()
    {	
		parent::_initialize();
		$this->adminfilepath = TMPL_PATH.$this->sysConfig['DEFAULT_THEME'].'/Public/billtemplate/';
		$this->dao=M('Order');
		
	}

    public function index()
    {
		$type=  'html';
		$path=$this->adminfilepath;
		$files = dir_list($path,$type);
		foreach ($files as $key=>$file){
			$filename = basename($file);
			$templates[$key]['value'] =  substr($filename,0,strrpos($filename, '.'));
			$templates[$key]['filename'] = $filename;
			$templates[$key]['filepath'] = $file;
			$templates[$key]['filesize']=byte_format(filesize($file));
			$templates[$key]['filemtime']=filemtime($file);
			$templates[$key]['ext'] = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)));
		}
		$this->assign ( 'templates',$templates );
		$template =  file_exists(TEMPLATE_PATH.'/'.GROUP_NAME.'/'.MODULE_NAME.'_index.html') ? MODULE_NAME.'_index' : 'content_index';
	    $this->_list('order');
		$this->assign ( 'username', $_GET['username'] );
		$this->assign ( 'website1', M('website') -> select() );
if($_GET['pdf']){
$this->outpdf();
}else{
		$_rs=M('role')->where('id='.$_SESSION['groupid'])->find();
		$this->assign ( 'orderfield',$_rs['orderfield'] );
        $this->display ($template);
}


    }
 
 	public function edit(){
		$sn = $_REQUEST['sn'];
		$id= $_REQUEST['id'];
		$model =M('Order');
		if($sn){
			$cart = $model->getBySn($sn); 
		}elseif($id){
		   $cart = $model->find($id); 
		}else{
			$this->error ( L('do_empty'));
		}
		$cart['productlist']=unserialize($cart['productlist']);

		foreach((array)$cart['productlist'] as $key =>$rs){
			$cart['totalnum'] +=$rs['num'];
			$cart['totalprice'] += $rs['num']*$rs['price'];
			$cart['productlist'][$key]['countprice'] = $rs['num']*$rs['price'];
		}
		$this->assign('cart',$cart);
		$this->display();
		
	}
	public function show(){
		$sn = $_REQUEST['sn'];
		$id= $_REQUEST['id'];
		$model =M('Order');
		if($sn){
			$cart = $model->getBySn($sn); 
		}elseif($id){
		   $cart = $model->find($id); 
		}else{
			$this->error ( L('do_empty'));
		}
		 
		$cart['productlist']=unserialize($cart['productlist']);

		foreach((array)$cart['productlist'] as $key =>$rs){
			$cart['totalnum'] +=$rs['num'];
			$cart['totalprice'] += $rs['num']*$rs['price'];
			$cart['productlist'][$key]['countprice'] = $rs['num']*$rs['price'];
		}
		$this->assign('cart',$cart);
		$this->display();
		
	}
	function update() {
		$model =M('Order');
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		if (false !== $model->save ()) {


if($_POST['status']==1){

//获取订单商品

	$mo_db=M('Order');
	if($mo_tmp=$mo_db->where('id='.$_POST['id'])->find()){
		$productlist=unserialize($mo_db->productlist);
		$mo_db=M('Stock');
		foreach((array)$productlist as $rs){
			$mo_tmp=$mo_db->setDec('number','productcode="'.$rs['productcode'].'"',$rs['num']);
		}
	}
}
			if(in_array($name,$this->cache_model)) savecache($name);
			$this->success (L('edit_ok'));
		} else {
			$this->success (L('edit_error').': '.$model->getDbError());
		}
	}
	public function outpdf()
	{
		$this->_list(MODULE_NAME);
 //       $this->display ();
include("Yourphp/Lib/tcpdf/config/lang/eng.php");
require_once('Yourphp/Lib/tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Mo');
$pdf->SetTitle('订单列表');
$pdf->SetSubject('订单列表');
$pdf->SetKeywords('订单列表');
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 038', PDF_HEADER_STRING);
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->setLanguageArray($l);
$pdf->SetFont('stsongstdlight', '', 20);
$pdf->AddPage();
//$pdf->write(0, $this->fetch ($template), '', 0, 'L', true, 0, false, false, 0);
$pdf->writeHTML($this->fetch ('Order_outpdf'), true, 0, true, 0);
$pdf->Output('example_038.pdf', 'I');

	}
	protected function _list($modelname, $map = '', $sortBy = '', $asc = false ,$listRows = 15) {
		$model = M($modelname);
		$id=$model->getPk ();
		$this->assign ( 'pkid', $id );

		if (isset ( $_REQUEST ['order'] )) {
			$order = $_REQUEST ['order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $id;
		}
		if (isset ( $_REQUEST ['sort'])) {
			$_REQUEST ['sort']=='asc' ? $sort = 'asc' : $sort = 'desc';
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}

		$_REQUEST ['sort'] = $sort;
		$_REQUEST ['order'] = $order;
		$keyword=$_REQUEST['keyword'];
		$searchtype=$_REQUEST['searchtype'];
		$groupid =intval($_REQUEST['groupid']);
		$catid =intval($_REQUEST['catid']);
		$posid =intval($_REQUEST['posid']);
		$typeid =intval($_REQUEST['typeid']);
		if(!empty($keyword) && !empty($searchtype)){
			$map[$searchtype]=array('like','%'.$keyword.'%');
		}


if($_REQUEST['startdate'] && $_REQUEST['enddate']){
//时间查询
		$_REQUEST['startdate']=strtotime($_REQUEST['startdate']);
		$_REQUEST['enddate']=strtotime($_REQUEST['enddate']);
		define('Halfofday',60*60*24-1);
		$_REQUEST['enddate']=$_REQUEST['enddate']+Halfofday;
		$map['createtime']=array(array('gt',$_REQUEST['startdate']),array('lt',$_REQUEST['enddate'])) ;
}

$map['ispayment']=1;
$map2['ispayment']=1;
if($map['createtime']){$map2['createtime']=$map['createtime'];}
		if($groupid)$map['groupid']=$groupid;
		if($catid)$map['catid']=$catid;
		if($posid)$map['posid']=$posid;
		if($typeid) $map['typeid']=$typeid;
		if(isset($_REQUEST['status']) && ( $_REQUEST['status']==='0' || $_REQUEST['status']>0)){
			$map['status']=intval($_REQUEST['status']);
		}else{
			unset($_REQUEST['status']);
		}

		$this->assign($_REQUEST);
		//取得满足条件的记录总数
		$count = $model->where ( $map )->count ( $id );
		if ($count > 0) {
			import ( "@.ORG.Page" );
			//创建分页对象
			if (! empty ( $_REQUEST ['listRows'] )) {
				$listRows = $_REQUEST ['listRows'];
			}
			$p = new Page ( $count, $listRows );
			//分页查询数据
			$field=$this->module[$this->moduleid]['listfields'];
$voList=array();

if(empty($_REQUEST['top'])){

if($_REQUEST['searchtype']=='saleser' or $_REQUEST['searchtype']=='country'){
//国家或者销售员查询
	if($_REQUEST['searchtype']=='country'){$tmp_field='country';$tmp_note='国家：';}else{$tmp_field='saleser';$tmp_note='销售员：';}
	if(isset($map2[$tmp_field])){unset($map2[$tmp_field]);}
	$map2[$tmp_field] = array('like','%'.trim($_REQUEST['keyword']).'%');
	$saleserarr=$model->field($tmp_field)->where($map2)->select();
	foreach($saleserarr as $k=>$val){$salesertmp[$k]=$val[$tmp_field];}
	$saleserarr=array_unique($salesertmp);
	unset($k);unset($val);
	foreach($saleserarr as $k=>$val){
		if(isset($map2['domain'])){unset($map2['domain']);}
		if(isset($map2[$tmp_field])){unset($map2[$tmp_field]);}
		$map2[$tmp_field] = $val;
		$b=$model->field('domain')->where($map2)->select();
		foreach($b as $k2=>$val2){$bb[$k2]=$val2['domain'];}
		$b=array_unique($bb); //网站名称
		unset($k2);unset($val2);
		$temp_aa=0;
		foreach($b as $k2 =>$val2){
			$temp_a=0;
			$temp_b=0;
			$temp_c=0;
			$temp_d=0;
			$map2['domain']=$val2;
			$c=$model->where($map2)->select();  //订单
			foreach($c as $k3=>$val3){
				$c[$k3]['yunfei']=0;
				$c[$k3]['num']=0;
				$c[$k3]['one_price']=0;
				$val3['productlist']=unserialize($val3['productlist']);
				$c[$k3]['sublist']=$val3['productlist'];  //产品
				foreach($c[$k3]['sublist'] as $k4=>$val4){
					$c[$k3]['one_price']+=$val4['price'];
					$c[$k3]['num']+=$val4['num'];
				}
				$c[$k3]['yunfei']=$c[$k3]['price']-$c[$k3]['one_price'];
				$temp_a+=$c[$k3]['price'];
				$temp_b+=$c[$k3]['num'];
				$temp_c+=$c[$k3]['yunfei'];
				$temp_d+=$c[$k3]['one_price'];
			}
			unset($b[$k2]);
			$b[$k2]=array('domain'=>$val2,'sublist'=>$c,'currency'=>$val3['currency'],'one_price'=>$temp_d,'num'=>$temp_b,'yunfei'=>$temp_c,'n_price'=>$temp_a);
			$a=M('website')->field('abbreviationb')->where('domain="'.$val2.'"')->find();
			$temp_a=$a['abbreviationb']*$temp_a;
			$temp_aa+=$temp_a;
		}
		unset($saleserarr[$k]);
		$val=$tmp_note.$val;
		$saleserarr[$k]=array('saleser'=>$val,'sublist'=>$b,'price'=>$temp_aa);
		unset($b);unset($bb);
	}
	$this->assign ( 'saleserarr', $saleserarr );
}elseif($_REQUEST['searchtype']=='domain'){
//网站名称查询

	$map2['domain'] = array('like','%'.trim($_REQUEST['keyword']).'%');
	$domainarr=$model->field('domain')->where($map2)->select();
	foreach($domainarr as $k=>$val){$domaintmp[$k]=$val['domain'];}
	$domainarr=array_unique($domaintmp);
	unset($k);unset($val);
	$temp_aa=0;
	foreach($domainarr as $k2 =>$val2){
		$temp_a=0;
		$temp_b=0;
		$temp_c=0;
		$temp_d=0;
		$map2['domain']=$val2;
		$c=$model->where($map2)->select();  //订单
		foreach($c as $k3=>$val3){
			$c[$k3]['yunfei']=0;
			$c[$k3]['num']=0;
			$c[$k3]['one_price']=0;
			$val3['productlist']=unserialize($val3['productlist']);
			$c[$k3]['sublist']=$val3['productlist'];  //产品
			foreach($c[$k3]['sublist'] as $k4=>$val4){
				$c[$k3]['one_price']+=$val4['price'];
				$c[$k3]['num']+=$val4['num'];
			}
			$c[$k3]['yunfei']=$c[$k3]['price']-$c[$k3]['one_price'];
			$temp_a+=$c[$k3]['price'];
			$temp_b+=$c[$k3]['num'];
			$temp_c+=$c[$k3]['yunfei'];
			$temp_d+=$c[$k3]['one_price'];
		}
		unset($domainarr[$k2]);
		$domainarr[$k2]=array('domain'=>$val2,'sublist'=>$c,'currency'=>$val3['currency'],'one_price'=>$temp_d,'num'=>$temp_b,'yunfei'=>$temp_c,'n_price'=>$temp_a);
		$a=M('website')->field('abbreviationb')->where('domain="'.$val2.'"')->find();
		$temp_a=$a['abbreviationb']*$temp_a;
		$temp_aa+=$temp_a;
	}
	$this->assign ( 'domainarr_c', $domainarr );
}elseif(($_REQUEST['searchtype']=='day' or $_REQUEST['searchtype']=='month') and isset($map2['createtime'])){
//销售统计
	$a=$model->where($map2)->select();
	$price='';
	foreach($a as $k3=>$val3){
		$val3['productlist']=unserialize($val3['productlist']);
		$a[$k3]['sublist']=$val3['productlist'];  //产品
		$price+=$val3['price'];
	}
	$this->assign ( 'price', $price );
	$this->assign ( 'day_c', $a );
}elseif($_REQUEST['searchtype']=='productcode'){




}
}else{

if($_REQUEST['top']=='guest'){
//客户排行
	$a=$model->field('email')->where($map2)->select();
	if(!$a){return;}
	foreach($a as $k=>$val){$b[$k]=$val['email'];}
	$a=array_unique($b);
	unset($k);unset($val);unset($b);
	foreach($a as $k=>$val){
		$map2['email']=$val;
		if(isset($map2['domain'])){unset($map2['domain']);}
		$b=$model->field('domain')->where($map2)->select();
		foreach($b as $kb=>$valb){$c[$kb]=$valb['domain'];}
		$b=array_unique($c);
		unset($kb);unset($valb);unset($c);

		foreach($b as $valb){
			$d=M('website')->field('abbreviationb')->where('domain="'.$valb.'"')->find();
			$map2['domain']=$valb;
			$c=$model->where($map2)->select();  //订单
			$price='';
			foreach($c as $k2=>$val2){
				$val2['productlist']=unserialize($val2['productlist']);
				$c[$k2]['sublist']=$val2['productlist'];  //产品
				$c[$k2]['pbody']='';
				foreach($c[$k2]['sublist'] as $k3=>$val3){
					$c[$k2]['pbody'].=$val3['pbody'];
				}
				$price+=$c[$k2]['price'];
			}
			unset($a[$k]);
			$price=$d['abbreviationb']*$price;
			$a[$k]=array('email'=>$val,'sublist'=>$c,'price'=>$price);

		}
	}
	$tmp = array();
	foreach($a as $k=>$val){$tmp[$k]=$val['price'];}
	arsort($tmp);
	$newtmp = array();
	foreach($tmp as $k => $v){
		if($k>50){break;}
		$newtmp[] = $a[$k];
	}
	$a=$newtmp;
	$this->assign ( 'guest_a', $a );
}elseif($_REQUEST['top']=='saleser'){
//销售员排行
	$a=$model->field('saleser')->where($map2)->select();
	if(!$a){return;}
	foreach($a as $k=>$val){$b[$k]=$val['saleser'];}
	$a=array_unique($b);
	unset($k);unset($val);unset($b);
	if($map['createtime']){$createtime='&startdate='.date('Y-m-d',$_REQUEST['startdate']).'&enddate='.date('Y-m-d',$_REQUEST['enddate']);}
	foreach($a as $k=>$val){
		$map2['saleser']=$val;
		$b=$model->field('domain')->where($map2)->select();
		if(isset($c)){unset($c);}
		foreach($b as $kb=>$valb){$c[$kb]=$valb['domain'];}
		$b=array_unique($c);
		unset($kb);unset($valb);unset($c);
		$price_a='';
		foreach($b as $kb=>$valb){
			$d=M('website')->field('abbreviationb')->where('domain="'.$valb.'"')->find();
			$map2['domain']==$valb;
			$c=$model->where($map2)->select();
			foreach($c as $valc){
			$price_a+=($valc['price']*$d['abbreviationb']);
			}
		}
		$a[$k]=array('saleser'=>$val,'price'=>$price_a,'url'=>U($module_name.'/index').'&searchtype=saleser&keyword='.$val.$createtime);
	}
	$tmp = array();
	foreach($a as $k=>$val){$tmp[$k]=$val['price'];}
	arsort($tmp);
	$newtmp = array();
	foreach($tmp as $k => $v){
		$newtmp[] = $a[$k];
	}
	$a=$newtmp;
	$this->assign ( 'saleser_a', $a );
}elseif($_REQUEST['top']=='goods'){
//商品查询
	$query = "CREATE TEMPORARY TABLE IF NOT EXISTS yourphp_tbl(id int(11) not null auto_increment primary key,pro_code varchar(255),country varchar(255),num int(16)) ENGINE=MyISAM DEFAULT CHARSET=utf8";
	$Model_1 = new Model();
	$Model_1->execute($query);
	$Model_1 = new Model('tbl');
	$a=$model->where($map2)->select();
	foreach($a as $val2){
		$val2['productlist']=unserialize($val2['productlist']);
		foreach($val2['productlist'] as $val3){
			$data['pro_code'] = $val3['productcode'];
			$data['country'] = $val2['country'];
			$data['num'] = $val3['num'];
			$Model_1->add($data);
		}
	}
$a=$Model_1->select();
foreach($a as $k=>$val){$b[$k]=$val['pro_code'];}
$a=array_unique($b);//不重复的产品编码
unset($k);unset($val);unset($b);
$i=0;
$aa=array();
foreach($a as $val){$aa[$i]['pro_code']=$val;$aa[$i]['country']=array();$aa[$i]['t_num']=0;$i++;}
$a=$aa;
unset($aa);unset($i);
foreach($a as $k=>$val){
	$b=0;
	$b=$Model_1->where('pro_code="'.$val['pro_code'].'"')->select();
	$a[$k]['t_num']=$Model_1->where('pro_code="'.$val['pro_code'].'"')->sum('num');
	$c=array();
	foreach($b as $val2){$c[]=$val2['country'];}
	$b=array_unique($c);//不重复的国家
	unset($val2);unset($c);
	foreach($b as $k2=>$val2){
		$country_num=0;
		$country_num=$Model_1->where('pro_code="'.$val['pro_code'].'" and country="'.$val2.'"')->sum('num');
		$b[$k2]=array('country'=>$val2,'num'=>$country_num);
	}
	$a[$k]['country']=$b;
}
	$tmp = array();
	foreach($a as $k=>$val){$tmp[$k]=$val['t_num'];}
	arsort($tmp);
	$newtmp = array();
	foreach($tmp as $k => $v){
		$newtmp[] = $a[$k];
	}
	$a=$newtmp;
$this->assign ( 'pro_code_', $a );
}

}





















			//分页跳转的时候保证查询条件
			foreach ( $map as $key => $val ) {
				if (! is_array ( $val )) {
					$p->parameter .= "$key=" . urlencode ( $val ) . "&";
				}
			}
			$map[C('VAR_PAGE')]='{$page}';
			$page->urlrule = U($modelname.'/index', $map);
			//分页显示
			$page = $p->show ();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			//模板赋值显示
			$this->assign ( 'list', $voList );
			$this->assign ( 'page', $page );
		}
		return;
	}


    public function bill()
    {


$ids=$_POST['ids'];
if(!empty($ids) && is_array($ids)){
	$id=implode(',',$ids);
	$tmpdata=M('order')->where('id in ('.$id.')')->select();


foreach($tmpdata as $k=>$val){


$this->assign ( 'consignee'.$k, $val['consignee'] );
$this->assign ( 'address'.$k, $val['address'] );
$this->assign ( 'trackcode'.$k, $val['trackcode'] );

}




include("Yourphp/Lib/tcpdf/config/lang/eng.php");
require_once('Yourphp/Lib/tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Mo');
$pdf->SetTitle('订单列表');
$pdf->SetSubject('订单列表');
$pdf->SetKeywords('订单列表');
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 038', PDF_HEADER_STRING);
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->setLanguageArray($l);
$pdf->SetFont('stsongstdlight', '', 20);
$pdf->AddPage();
//$pdf->write(0, $this->fetch ($template), '', 0, 'L', true, 0, false, false, 0);
$pdf->writeHTML($this->fetch ('Yourphp/Tpl/Default/Public/billtemplate/'.$_POST['template']), true, 0, true, 0);
$pdf->Output('example_038.pdf', 'I');



}else{echo'no data';}

    }

}
?>